# -*- coding:UTF-8 -*-
from django.http import JsonResponse, HttpResponse
import json
from django.contrib.auth.decorators import login_required


# 查询用户的所有未读通知
@login_required()
def get_unread_notice(request):
    if request.method == "GET":
        notice_list = request.user.notifications.unread()
        if len(notice_list) > 0:
            for notice in notice_list:
                ctx = {
                    'actor': notice.actor.name,
                    'verb': notice.verb,
                    'action_object': notice.action_object,
                    'target': notice.target.code.name,
                    'timesince': notice.timesince()
                }
                if notice.target:
                    if notice.action_object:
                        data = u'%(actor)s %(verb)s %(action_object)s on %(target)s %(timesince)s 以前' % ctx
                        return HttpResponse(data)
                    data = u'%(actor)s %(verb)s %(target)s %(timesince)s 以前' % ctx
                    return HttpResponse(data)
                if notice.action_object:
                    return HttpResponse(u'%(actor)s %(verb)s %(action_object)s %(timesince)s 以前' % ctx)
                return HttpResponse(u'%(actor)s %(verb)s %(timesince)s 以前' % ctx)
        else:
            return HttpResponse("您没有未读的通知。")


# 将通知转换成已读信息
@login_required()
def update_unread_notice(request):
    if request.method == "POST":
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        # 如果传入notice_id 那么就将这条id为notice_id的notice改为已读
        try:
            notice_id = req_data['notice_id']
            request.user.notifications.get(id=notice_id).mark_as_read()
        # 如果未传入notice_id 则将全部notice改为已读
        except Exception as e:
            request.user.notifications.mark_all_as_read()
        data = {"success": True, "data": {"msg": "通知已查看"}}
        return JsonResponse(data)
